package com.zj.init;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.zj.common.MediaConstant;
import com.zj.server.MediaServer;
import com.zj.thread.MediaListenThread;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacpp.Loader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.InetSocketAddress;

/**
 * 启动流媒体
 */
@Slf4j
@Component
public class InitServer implements CommandLineRunner {

    @Value("${mediaserver.port}")
    private int port;

    @Autowired
    private MediaServer mediaServer;

    @Autowired
    private Environment env;

    @Override
    public void run(String... args) throws Exception {
        ThreadUtil.execute(new MediaListenThread());
        String ip = InetAddress.getLocalHost().getHostAddress();
        String httpPort = env.getProperty("server.port");
        String path = env.getProperty("server.servlet.context-path");
        if (StrUtil.isEmpty(path)) {
            path = "";
        }
        log.info("\n--------------------------------------------------------- \n" +
                        "\t EasyMedia is running! Access address: \n" +
                        "\t media port at : \t {} \n" +
                        "\t http port at : \t {} \n" +
                        "\t web Local: \t http://localhost:{} \n" +
                        "\t web External: \t http://{}:{}{} \n" +
                        "\t httpflv: \t http://{}:{}/live?url={您的源地址} \n" +
                        "\t wsflv: \t ws://{}:{}/live?url={您的源地址} \n" +
                        "\t hls(m3u8): \t http://{}:{}/hls?url={您的源地址} \n" +
                        "--------------------------------------------------------- \n",
                port,
                httpPort,
                httpPort,
                ip, httpPort, path,
                ip, port,
                ip, port,
                ip, httpPort,
                ip, httpPort);
        mediaServer.start(new InetSocketAddress("0.0.0.0", port));
    }

    /**
     * 提前初始化，可避免推拉流启动耗时太久
     */
    @PostConstruct
    public void loadFFmpeg() {

        /**
         * 初始化ffmpeg路径
         */
       /* String ffmpeg = Loader.load(org.bytedeco.ffmpeg.ffmpeg.class);
        System.setProperty(MediaConstant.ffmpegPathKey, ffmpeg);*/
        log.info("初始化资源成功");
    }
}
